package com.stack.wemedia.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.stack.apis.admin.IAdminClient;
import com.stack.apis.article.IArticleClient;
import com.stack.common.aliyun.GreenImageScan;
import com.stack.common.aliyun.GreenTextScan;
import com.stack.file.service.FileStorageService;
import com.stack.model.admin.dtos.AdNewsDto;
import com.stack.model.article.dtos.ArticleDto;
import com.stack.model.common.dtos.ResponseResult;
import com.stack.model.wemedia.pojos.WmChannel;
import com.stack.model.wemedia.pojos.WmNews;
import com.stack.model.wemedia.pojos.WmUser;
import com.stack.wemedia.mapper.WmChannelMapper;
import com.stack.wemedia.mapper.WmNewsMapper;
import com.stack.wemedia.mapper.WmUserMapper;
import com.stack.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author llz
 * @date 2023/10/12 11:22
 * @description
 */

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Resource
    private WmNewsMapper wmNewsMapper;

    @Resource
    private WmChannelMapper wmChannelMapper;

    @Resource
    private WmUserMapper wmUserMapper;

//    @Qualifier("com.stack.apis.article.IArticleClient")
//    @Autowired
    @Resource
    private IArticleClient articleClient;

    @Resource
    private IAdminClient adminClient;

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private GreenImageScan greenImageScan;

    @Resource
    private GreenTextScan greenTextScan;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async  //标明当前方法是一个异步方法
    public void autoScanWmNews(Integer id) {

//        int a = 1/0;
        log.info("id:{}", id);
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        log.info("wmNews:{}", wmNews);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //TODO 需要付费 暂不可用
//            //从内容中提取纯文本内容和图片
//            Map<String, Object> textAndImages = handleTextAndImages(wmNews);
//
//            //优化 新增审核标题
//            //2.审核文本内容以及标题  阿里云接口
//            try {
//                boolean isTextScan = handleTextScan((String) textAndImages.get("content"), wmNews);
//                boolean textScan = handleTextScan((String) textAndImages.get("title"), wmNews);
//                if (!isTextScan) return;
//                if (!textScan) return;
//
//                //3.审核图片  阿里云接口
//                boolean isImageScan = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
//                if (!isImageScan) return;
//            } catch (Exception e) {
//                updateWmNews(wmNews, (short) 2, "审核失败");
//                log.info("自动审核失败转换人工审核-------------------2");
//                return;
//            }

            //4.审核成功
            //保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            log.info("getCode:{}", responseResult.getCode());
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, (short) 9, "已发布");
        }
    }

    /**
     * 保存app端相关的文章数据
     *
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        log.info("保存的文章:{}", JSON.toJSONString(dto));
        ResponseResult responseResult = articleClient.saveArticle(dto);

        return responseResult;
    }



    /**
     * 审核图片
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if (images == null || images.size() == 0) {
            return flag;
        }

        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }


        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }



    /**
     * 审核纯文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        if ((wmNews.getTitle() + "-" + content).length() == 0) {
            return flag;
        }

        try {
            Map map = greenTextScan.greeTextScan((wmNews.getTitle() + "-" + content));
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;

    }

    /**
     * 修改文章内容
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 1。从自媒体文章的内容中提取文本和图片
     * 2.提取文章的封面图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        //1.从自媒体文章的内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }

                if (map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }
        //2.提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        //3.提取标题
        String title = wmNews.getTitle();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", images);
        resultMap.put("title", title);
        return resultMap;

    }
}
